import axios from 'axios';
import { useRouter } from 'vue-router';
import { SignUtil } from '@/util/signin';
import Cookies from 'js-cookie';
const router = useRouter();
const ServerCache = {};

const BUSINESSFLAG="questionbank";
//加上业务系统标志
const addBusinessFlag=(value)=>{
	return BUSINESSFLAG+"_"+value;
}
const getAuServer = () => {
	const key = '/bussServer';// 注意此处为了实现跨域，必须在vite.config.ts中配置跨域代理，用代理中的值代替模板服务器地址
	if (ServerCache[key]) {
		return ServerCache[key];
	} else {
		let server = axios.create({
			baseURL: key,
			timeout: 2000,
			withCredentials : true //该值表示携带cookie向服务端发送请求
		});
		ServerCache[key] = server;
		return server;
	}
};
const generateHeader=()=>{
	let _headers = {};
	_headers['Access-Control-Allow-Origin'] = '*';
	return _headers;
}
const appendFormSubmitHeader=(header)=>{
	if(header){
	header['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
	}
}
const appendJsonSubmitHeader=(header)=>{
	if(header){
	header['Content-Type'] = 'application/json;charset=UTF-8';
	}
}
export const BuServerUtil = {
	getSession: async()=>{
		let _server = getAuServer();
		let _data = {
		};
		let _headers = generateHeader();
		appendFormSubmitHeader(_headers);
		let url = '/login/getSession';
		await _server
			.get(url, _data, {
				headers: _headers
			})
			.then(res => {
				console.log(res);
				let code=res.data['code']
				if (code==200) {
					Cookies.set('JSESSIONID', res.data['sessionid']);
				} else {
					console.log("session获取失败！");
				}
			})
			.catch(error => {
				console.log(error);
			});
	},
	toAuth: async(formData, authSuccess, authFailed) => {
		let _server = getAuServer();
		let _username=addBusinessFlag(formData.username);
		let _data = {
			username: _username,
			password: formData.password,
			checkCode:formData.checkCode
		};
		let _headers = generateHeader();
		appendFormSubmitHeader(_headers);
		let url = '/login';
		await _server
			.post(url, _data, {
				headers: _headers
			})
			.then(res => {
				console.log(res);
				let code=res.data['code']
				if (code==200) {
					//authSuccess(_data["username"],res.data);
				} else {
					//authFailed(res.data);
				}
			})
			.catch(error => {
				console.log(error);
				formData.message="用户名或密码错误！";
			});
	},
	toGetToken: async(authSuccess, authFailed) => {
		let _server = getAuServer();
		const _userInfor=SignUtil.getUserSigninInfo();
		let _data = {
			params:{
			userInDb: JSON.stringify(_userInfor["userInDb"]),
			loginName:_userInfor["loginName"]
			}
		}
		let _headers = generateHeader();

		appendFormSubmitHeader(_headers);
		let url = '/login/getToken';
		await _server
			.get(url, _data, {
				headers: _headers
			})
			.then(res => {
				console.log(res);
				let code=res.data['code']
				if (code==1020) {
					let _data=res.data['data'];
					let _token =JSON.parse(_data);
					authSuccess(_token);
				} else {
					authFailed(res.data);
				}
			})
			.catch(error => {
				console.log(error);
			});
	},
	toRefreshToken: async( refresh_token_str) => {
		if(!refresh_token_str){
			return;
		}
		let need2Refresh=SignUtil.needRefreshToken();
		if(true==need2Refresh){
			
		let _server = getAuServer();
		let _data = {
			refresh_token:refresh_token_str
		};

		let _headers = generateHeader();
		appendFormSubmitHeader(_headers);
		console.log(_data);
		//刷新令牌也是相同的url，但参数不同
		let url = '/login/refreshToken';
		await _server
			.post(url, _data, {
				headers: _headers
			})
			.then(res => {
				const _newToken=res.data;
				SignUtil.refreshToken(_newToken);
			})
			.catch(error => {
				console.log(error);
			});
	}
		}
};
